package com.itheima.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;

@WebServlet("/addStudent")
public class addStudent extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String age = request.getParameter("age");
        String score = request.getParameter("score");
        Student student = new Student();
        student.setUsername(username);
        student.setAge(Integer.parseInt(age));
        student.setScore(Integer.parseInt(score));
        ArrayList<Student> listStu = new ArrayList<>();
        listStu.add(student);
        String realPath = this.getServletContext().getRealPath("/stu.txt");
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(realPath,true),"UTF-8");
        BufferedWriter bw = new BufferedWriter(osw);
        for (Student student1 : listStu) {
            bw.write(student1.getUsername()+","+student1.getAge()+","+student1.getScore());
            bw.newLine();
        }
        bw.close();
        String contextPath = request.getContextPath();
        //response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("添加成功!三秒后返回首页.....");
        response.setHeader("Refresh","3;URL="+contextPath+"/index.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
